<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebSocket Logger</title>
    <script src="../public/plugins/xterm/sockjs.min.js"></script>
    <script src="../public/plugins/xterm/stomp.min.js"></script>
    
    <!-- 引入基础的css和js -->
    <link rel="import" href="../public/import.html" id="import"/>
    <link rel="stylesheet" href="../public/plugins/xterm/xterm.css">
    <script src="../public/plugins/xterm/xterm.js"></script>
</head>
<body>
 <div id="terminal"></div>
 <script>
 
   var term = new Terminal({
       cols: 130,
       rows: 38,
       /* cursorBlink: 5, 
       scrollback: 100,
       tabStopWidth: 4 */
   });
   term.open(document.getElementById('#terminal'));
   //term.fit();
   /* term.on('data', function($data) {
	  // ws.send($data);
	  //alert($data);
	  sendCmd($data);
	}); */
  // term.write('Hello from \033[1;3;31mxterm.js\033[0m $ ')
 </script>

<script>
	var shellIdStr = '';//跳转地址链接所带参数
	var shellId = '';//服务器的ID
	var type = '';//跳转页面类型，日志，启动，关闭
    var stompClient = null;
    var randomShellId = "";//代表当前shell对话的指定key，随机数加上服务器ID
    var path = "";//项目路径

    var vm = new Vue({
    	el:'#terminal',
    	data:{
    		showList: true,
    		title: null,
   		}
    });    
    
    $(document).ready(function() {
    	shellIdStr = GetQueryString("shellId");
    	shellId = shellIdStr.split('_')[0];
    	type = shellIdStr.split('_')[1];
    	var random = GetQueryString("random");
    	randomShellId = shellId + random;
    	openSocket();
    	var data = "";
	   	 $.ajax({
				type: "post",
				async: false,
			    url: $path+"sys/sysshell/info/"+shellId,
			    data: shellId,
			    success: function(r){
			    	path = r.sysShell.path;
			    }
		 }); 

    	if(type == 1){//日志打印
    		var level = GetQueryString("level");
    		data = 'tail -f ' + path + '/log/console.log |grep ' + level + '\r';
    	}else if(type == 2){//关闭系统
    		data = 'sh ' + path + '/nads.sh stop \r';
    	}else if(type == 3){//启动系统
    		data = 'sh ' + path + '/nads.sh start \r';
    	}
    	sendCmd(data);
    });
    function openSocket() {
        if(stompClient==null){
        	//var shellId = window.localStorage.shellId;
        	var socketPath = $path+'websocket?token=kl';
        	socketPath = socketPath.replace("http","ws");
            var socket = new WebSocket(socketPath);
            stompClient = Stomp.over(socket);
            var headers={
            		"Access-Control-Allow-Origin":"*",
            		"Access-Control-Allow-Credentials":"true",
            		"token":"kltoen"
            };
            stompClient.connect(headers, function(frame) {
                stompClient.subscribe('/'+randomShellId, function(event) {
                    //$("#log-container div").append(changeData(event.body)).append("<br/>");
                    //  $("#log-container").scrollTop(10000000);
                      term.write(event.body);
                },headers);
            });
            
            window.setInterval(function(){ //每隔5秒钟发送一次心跳，避免websocket连接因超时而自动断开
            	stompClient.send(" ");
            },30000);
        }
    }
    
    function GetQueryString(name){
         var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
         var r = window.location.search.substr(1).match(reg);
         if(r!=null)return  unescape(r[2]); return null;
    }

    function clean(){
    	$("#log-container div").html("");
    }
    function reconnect() {
        if (stompClient != null) {
            stompClient.disconnect();
            stompClient=null;
        }
        alert("关闭日志成功！");
    }
    
    $('#cmd').on('keypress',function(event){ 
        if(event.keyCode == 13)      
        {  
        	var object = {};
        	object["cmd"]=$('#cmd').val();
        	//object["id"]=window.localStorage.shellId;
        	object["id"]=shellId;
        	object["randomShellId"]=randomShellId;
        	 $.ajax({
					type: "post",
				    url: $path+"sys/sysshell/send",
				    data: JSON.stringify(object)
			 }); 
        	 $('#cmd').val("");
        }  
    });
    
    function sendCmd(data){
    	var object = {};
    	object["cmd"]=data;
    	//object["id"]=window.localStorage.shellId;
    	object["id"]=shellId;
    	object["randomShellId"]=randomShellId;
    	$.ajax({
			type: "post",
			url: $path+"sys/sysshell/send",
			data: JSON.stringify(object)
		});
    }
    
    String.prototype.replaceAll = function(s1,s2){ 
    	return this.replace(new RegExp(s1,'gm'),s2); 
    }
    function changeData(data){
    	data = data.replaceAll(" ","&nbsp;&nbsp;")
    	    .replaceAll("\\[01;34m","<span style='color:#00b0f0'>")
    	    .replaceAll("\\[01;31m","<span style='color:#ff0000'>")
    	    .replaceAll("\\[01;33m","<span style='color:#ffff00'>")
    	    .replaceAll("\\[01;32m","<span style='color:#92d050'>")
    	    .replaceAll("\\[01;35m","<span style='color:#AB82FF'>")
    	    .replaceAll("\\[01;36m","<span style='color:#B0E2FF'>")
    	    .replaceAll("\\[34;42","<span style='color:#92d050;background: #00FF00'>")
    	    .replaceAll("\\[0m","</span>")    	    
    	    .replaceAll("\\[m","");
    	return data;
    }
    
    window.onbeforeunload=function(e){  
    	var object = {};
    	//ctrl+c关闭进程
    	object["cmd"]="";
    	object["id"]=shellId;
    	object["randomShellId"]=randomShellId;
    	 $.ajax({
				type: "post",
			    url: "../sys/sysshell/send",
			    data: JSON.stringify(object)
		 }); 
	} 
   
</script>
</body>
</html>